package com.zhulong.saas.cloud.gateway.gwfilter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AddTenantIdFilter implements GlobalFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(AddAuthInfoFilter.class);

    @Value("${gw.tenantId.key:zl_tenantId}")
    private String tenantIdKey;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return Mono.subscriberContext()
                .flatMap(c -> {
                    Long tenantId = c.get("tenantId");
                    log.debug("进入租户设置，获取到租户id:" + tenantId);
                    ServerHttpRequest request = exchange.getRequest().mutate()
                            .header(tenantIdKey, tenantId == null ? "" : tenantId.toString()).build();
                    return chain.filter(exchange.mutate().request(request).build());
                });
    }

    @Override
    public int getOrder() {
        return 110;
    }
}
